package services;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import services.RequestService.ServiceWorker;
import com.rentapark.app.MainScreen;
import com.rentapark.app.R;
import data.DB;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

//this service is used when the user wants to buy credit
public class BuyCredit extends Service{
	private NotificationManager notificationMgr;
	private boolean runningFlag = false;
	public DB parking_db;
	int val=0;
	
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	//handles server responses
	private final Handler handler = new Handler() {  

		public void handleMessage(Message msg) {
			String result = msg.getData().getString("RESPONSE"); 
			Toast.makeText( getApplicationContext(),result,Toast.LENGTH_SHORT).show();
				runningFlag = false;
				BuyCredit.this.stopSelf();
		} 
	};
	//onCreate
	public void onCreate() {
		Log.d("Service","onCreate");

		notificationMgr =(NotificationManager)getSystemService(
				NOTIFICATION_SERVICE);
		displayNotificationMessage("buying credit..");
	}
	//onDestroy
	public void onDestroy() {
		// TODO Auto-generated method stub
		Log.d("Service","onDestroy");
		runningFlag=false;
		super.onDestroy();
	}
	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		Log.d("Service","onStart");
		super.onStart(intent, startId);
		Bundle bundle =intent.getExtras(); 
		val=bundle.getInt("toBuy");
		if(runningFlag==false)
		{
			runningFlag = true;
			Thread thr = new Thread(null, new ServiceWorker(), "BackgroundService");
			thr.start();
		}

	}
	@Override
	public boolean onUnbind(Intent intent) {
		// TODO Auto-generated method stub
		Log.d("Service","onUnbind");
		return super.onUnbind(intent);
	}

	private void displayNotificationMessage(String message)
	{
		Notification notification = new Notification(R.drawable.ss,
				message,System.currentTimeMillis());
		PendingIntent contentIntent =
				PendingIntent.getActivity(this, 0,new Intent(this, MainScreen.class), 0);
		notification.setLatestEventInfo(this, "Rent-A-Park",message,
				contentIntent);
		notificationMgr.notify(R.string.app_notification_id, notification);
	}
	//this ineer class sends an http post message to a servlet for buying credit
	class ServiceWorker implements Runnable
	{
		final ResponseHandler<String> responseHandler = new ResponseHandler<String>() {   
			public String handleResponse(HttpResponse response) {    

				HttpEntity entity = response.getEntity();   
				Log.d("service","runn");
				String result = null; 
				try { 
					result = data.CommonUtilities.inputStreamToString(entity.getContent());   
					Message message = new Message();     
					Bundle bundle = new Bundle();         
					bundle.putString("RESPONSE", result); 
					message.setData(bundle); 
					handler.sendMessage(message);         
				} catch (IOException e) { 
					Log.e("Class6",  " ", e); 
				} 
				return result; 
			} 
		}; 
		public void run() {
			 
			if (runningFlag){
				HttpClient httpclient = new DefaultHttpClient();
				parking_db=DB.getInstance();
				String url="http://";
				url+=parking_db.instanceDNS;
				url+=":8080/ParkAndLetPark/BuyCredit";
				Log.d("url is",url);
				HttpPost httppost = new HttpPost(url);
				try {
					try{

						DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
						DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
						//creating a new instance of a DOM to build a DOM tree.
						Document doc = docBuilder.newDocument();
						Element Request = doc.createElement("MSG_TYPE");
						Request.appendChild(doc.createTextNode("BUY_CREDIT"));
						doc.appendChild(Request);
						Element Userid=doc.createElement("USER_ID");
						Userid.appendChild(doc.createTextNode(Double.toString(parking_db.userID)));//can be 0 on newUser!!
						Request.appendChild(Userid);
						Element credit=doc.createElement("TO_BUY");
						credit.appendChild(doc.createTextNode(Integer.toString(val)));
						Userid.appendChild(credit);
						

						TransformerFactory factory = TransformerFactory.newInstance();
						Transformer transformer = factory.newTransformer();

						transformer.setOutputProperty(OutputKeys.INDENT, "yes");

						StringWriter sw = new StringWriter();
						StreamResult result = new StreamResult(sw);
						DOMSource source = new DOMSource(doc);
						transformer.transform(source, result);
						String xmlString = sw.toString();
						Log.d("xmlString","^^^^^^"+xmlString);


						StringEntity se = new StringEntity(xmlString); //XML as a string
						se.setContentType("text/xml"); //declare it as XML
						httppost.setEntity(se);

						String response = httpclient.execute(httppost,responseHandler);
						Log.d("Service","Response* "+response);
					}
					catch (ClientProtocolException e) {
						Log.e("LOGTAG", " " , e); 
					} catch (IOException e) {
						Log.e("LOGTAG", " " , e); 
					}

				}
				catch(Exception e)
				{
					Log.e("LOGTAG", " " , e); 
				}
			}
		}
	}




}
